const crypto = require('crypto');

// 系统调用摘要生成串
const plainText = 'kPJ@vxg%hAQU*hf6';
// 必须是16字节（128位）的密钥，用于AES-128-ECB
const aesKey = '<@kingshine123!>';
// 下载路径加密
const key = Buffer.from([60, 64, 107, 105, 110, 103, 115, 104, 105, 110, 101, 49, 50, 51, 33, 62]);
let userName = ""
// 1. 计算MD5摘要
function md5(text) {
  return crypto.createHash('md5').update(text).digest('hex');
}

// 2. AES加密
function aesEncrypt(text, key) {
  const cipher = crypto.createCipheriv('aes-128-ecb', Buffer.from(key, 'utf8'), null);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

// 3. 生成签名
function signature() {
  // a) 获取当前时间并格式化为字符串
  const today = new Date();
  const formattedDate = today.toISOString().slice(0, 10).replace(/-/g, '');

  // b) 连接摘要生成串和时间字符串
  const baseString = `${plainText}_${formattedDate}`;

  // c) 使用MD5对字符串进行摘要处理
  const md5String = md5(`${baseString}_${userName}`);

  // d) 将摘要和用户名连接
  const finalString = `${md5String}_${userName}`;

  // e) 使用AES算法加密
  const encrypted = aesEncrypt(finalString, aesKey);

  return encrypted;
}
// 获取 userName
function getUserName(userName1) {
  userName = userName1
}
function encrypt(text) {
  const cipher = crypto.createCipheriv('aes-128-ecb', key, null);
  cipher.setAutoPadding(true); // 设置自动填充为 PKCS#5
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

function decrypt(encryptedText) {
  const decipher = crypto.createDecipheriv('aes-128-ecb', key, null);
  decipher.setAutoPadding(true); // 设置自动填充为 PKCS#5
  let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}
module.exports = {
  signature,
  getUserName,
  encrypt,
  decrypt
}